/** 处理视频预加载 */
import { Product, Subscription } from 'react-native-iap';

import NetInfo from '@react-native-community/netinfo';
import { get } from 'lodash';

import { mediaPreload } from '@/utils/mediaCache/preloadManager';
import PayServer from '@/utils/pay';

export const videoPreload = async (videoUrls: (string | undefined)[]) => {
  try {
    const netInfo = await NetInfo.fetch();
    if (!netInfo.isConnected) {
      console.log('Skip preload on no network');
      return;
    }

    const urls = videoUrls.filter((url): url is string => typeof url === 'string' && url.trim() !== '');

    const validUrls = [...new Set(urls)];

    if (validUrls.length > 0) {
      mediaPreload.addVideos(validUrls);
      // mediaPreload.startPreload(progress => {
      //   // console.log(`Videos preload progress: ${progress.toFixed(1)}%`);
      // });
    }
  } catch (error) {
    console.error('Failed to preload videos:', error);
  }
};

/** 从配置中提取需要预加载的视频URL */
export const extractVideosFromConfig = (config: Paywall.PaywallConfig): string[] => {
  const videos = [];

  // 推荐:统一维护预加载的视频列表
  if (config?.preloadVideoUrls) {
    videos.push(...config.preloadVideoUrls);
  }

  if (config?.backGroundVideo?.videoUrl) {
    videos.push(config.backGroundVideo.videoUrl);
  }
  // 如果还有其他视频，可以在这里添加
  // if (config?.otherVideos) {
  //   videos.push(...config.otherVideos);
  // }

  return videos;
};

/**  预加载订阅页面的视频资源 */
export const preloadSubscriptionVideos = async (config?: Paywall.PaywallConfig) => {
  if (!config) {
    console.warn('config is empty');
    return;
  }
  const videoUrls = extractVideosFromConfig(config);
  if (videoUrls.length === 0) {
    console.warn('No videos to preload');
    return;
  }
  videoPreload(videoUrls).catch((error) => {
    console.error('Video preload failed:', error);
  });
};

/** 获取价格和货币 */
export const getPriceAndCurrency = (product?: Subscription | Product) => {
  if (!product) return;
  // 判断是否是购买商品
  if (PayServer.IsProduct(product)) {
    const priceAmountMicros = +get(product, 'oneTimePurchaseOfferDetails.priceAmountMicros', '0');
    const price = priceAmountMicros / 1000000;
    const currency = get(product, 'oneTimePurchaseOfferDetails.priceCurrencyCode', 'USD');
    return { price, currency };
    // 判断是否是购买订阅
  } else if (PayServer.IsSubscription(product)) {
    const priceAmountMicros = +get(
      product,
      'subscriptionOfferDetails.0.pricingPhases.pricingPhaseList.0.priceAmountMicros',
      '0',
    );
    const price = priceAmountMicros / 1000000;
    const currency = get(
      product,
      'subscriptionOfferDetails.0.pricingPhases.pricingPhaseList.0.priceCurrencyCode',
      'USD',
    );
    return { price, currency };
  }
};
